interface ExtendedMath extends Math {
  easeInOutQuad(t: number, b: number, c: number, d: number): number;
}

(Math as ExtendedMath).easeInOutQuad = function(t: number, b: number, c: number, d: number): number {
  t /= d / 2
  if (t < 1) {
    return c / 2 * t * t + b
  }
  t--
  return -c / 2 * (t * (t - 2) - 1) + b
}

// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
const requestAnimFrame = window.requestAnimationFrame ||
  ((callback: FrameRequestCallback) => window.setTimeout(callback, 1000 / 60))

/**
 * Because it's so fucking difficult to detect the scrolling element, just move them all
 * @param {number} amount
 */
function move(amount: number): void {
  document.documentElement.scrollTop = amount
  if (document.body.parentElement) {
    document.body.parentElement.scrollTop = amount
  }
  document.body.scrollTop = amount
}

function position(): number {
  return document.documentElement.scrollTop || 
    (document.body.parentElement ? document.body.parentElement.scrollTop : 0) || 
    document.body.scrollTop
}

/**
 * @param {HTMLElement} element
 * @param {number} to
 * @param {number} duration
 */
export function scrollTo(element: HTMLElement, to: number, duration: number): void {
  if (duration <= 0) return
  const difference = to - element.scrollTop
  const perTick = difference / duration * 10

  setTimeout(() => {
    element.scrollTop = element.scrollTop + perTick
    if (element.scrollTop === to) return
    scrollTo(element, to, duration - 10)
  }, 10)
}
